/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package player;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;


/*
 * 
 * SocketTCPClient XML
 * Matthieu PERRIN
 * Communique avec le manager
 * 
 */
public class SocketTCPClient {
    
    private String manager;
    private String ID;
    private int port = 443;
        Socket clientSocket = null;
    
    public SocketTCPClient(String relay_manager_IP)
    {
        this.manager = relay_manager_IP;
    }

    private String Request(String msg) 
    {
        String reponse = "";
        try {

            clientSocket = new Socket(manager, port);

            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            // Envoie le message
            outToServer.writeBytes(msg + '\n');
            outToServer.flush();

            // Recupere la reponse
            reponse = inFromServer.readLine();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try
            {
            // Ferme la socket
                clientSocket.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        
        // retourne la reponse
        return reponse;
    }
    
    public String getProvider(String ID) 
    {
        String message = "1" + ID;
        
        String rep = Request(message);
        
        if ( rep.charAt(0) == '2')
            return rep.substring(1);
        else
            return null;
    }
    
    public void addProvider(String ID, String IP) 
    {
        this.ID = ID;
        String message = "3" + ID + '+' + IP;        
        Request(message);
    }
    
    public void delProvider(String ID, String IP) 
    {
        String message = "5" + ID + '+' + IP;
        Request(message);
    }
    
    
    public String getAdd()
    {
        return clientSocket.getLocalAddress().toString();
    }
}
